<?php

require 'MultiCurl.php';

/*
 * 构造MultiCurl对象时，可以传递所有Request共有的curl属性数组
 * 缺省选项如下：
 * CURLOPT_RETURNTRANSFER => true
 * CURLOPT_NOSIGNAL => 1
 */
$multi = new MultiCurl(
	array(
		CURLOPT_ENCODING => 'gzip',
		CURLOPT_FOLLOWLOCATION => 1
	));

// 继承MultiCurlRequest类，实现自己的处理函数
class Request extends MultiCurlRequest {
	public function process($resultCode, $info, $content) {
		echo 'request: ', $this->url, "<br/>\n";
		echo "resultCode: {$resultCode}<br/>\n";
	}
};

// 普通请求
$multi->addRequest(
	new Request('http://www.sina.com.cn/'));	

	
// 指定请求参数, 会覆盖构造MultiCurl时的缺省参数
$multi->addRequest(
	new Request('http://www.sohu.com/', null,
		array(
			CURLOPT_FOLLOWLOCATION => 0,
			CURLOPT_TIMEOUT_MS => 500 // 请求单独的超时设置
		)
	));
	
// post请求
// $multi->addRequest(new Request('http://localhost/post.php', 'a=1&b=222'));

// 添加请求时，可以指定重试次数
$multi->addRequest(new Request('http://www.163.com/', null,
	array(
		CURLOPT_CONNECTTIMEOUT_MS => 500,
		CURLOPT_TIMEOUT_MS => 500
	)), 1);

// execute阻塞执行，等所有请求结束，或者回调代码中调用了$multi->finish()才会返回
$multi->execute();


// 可以在回调函数中中止multi的执行
class FastRequest  extends MultiCurlRequest {
	public function process($resultCode, $info, $content) {
		echo "FastRequest result: ", $this->url, "<br/>\n";
		global $multi;
		$multi->finish();
	}
};
$multi->addRequest(new FastRequest('http://www.sina.com.cn/'));
$multi->addRequest(new FastRequest('http://www.baidu.com/'));

// 可以多次调用execute
$multi->execute();


// 可以在一个请求的回调中，结束另外一个请求，未删除的请求会继续执行
class WinnerRequest  extends MultiCurlRequest {
	private $cancelLst = array();
	
	public function addCancel($requestInfo) {
		$this->cancelLst[] = $requestInfo;
	}
	
	public function process($resultCode, $info, $content) {
		echo "WinnerRequest got result: ", $this->url, "<br/>\n";
		global $multi;
		foreach ($this->cancelLst as $cancelRequestInfo) {
			$multi->removeRequestChannel($cancelRequestInfo);
		}
	}
}

$req1 = new WinnerRequest('http://www.sina.com.cn/');
$reqInfo1 = $multi->addRequest($req1);
$req2 = new WinnerRequest('http://www.sohu.com/');
$reqInfo2 = $multi->addRequest($req2);

$req1->addCancel($reqInfo2);
$req2->addCancel($reqInfo1);

// 在删除一个请求后，其他的请求可以照常执行
$multi->addRequest(new Request('http://www.baidu.com/'));
$multi->execute();


// 可以在一个请求的回调中，添加另外的请求
class SinaRequest  extends MultiCurlRequest {
	public function __construct() {
		parent::__construct('http://news.sina.com.cn/');
	}
	
	public function process($resultCode, $info, $content) {
		echo "SinaRequest got result<br/>\n";
		global $multi;
		$multi->addRequest(new Request('http://www.sohu.com/'));
	}
};
$multi->addRequest(new SinaRequest());


$multi->execute();



echo "OKay<br/>\n";

